import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';

import { ConfigModule, ConfigService } from '@nestjs/config';
import { TypeOrmModule } from '@nestjs/typeorm';
import { ServeStaticModule } from '@nestjs/serve-static';
import { TournamentModule } from './modules/tournament/tournament.module';
import { CategoryModule } from './modules/category/category.module';
import { EventModule } from './modules/event/event.module';
import { StageModule } from './modules/stage/stage.module';
import { GroupModule } from './modules/group/group.module';
import { MatchModule } from './modules/match/match.module';
// import { TeamModule } from './modules/team/team.module';
import { UserModule } from './modules/user/user.module';
import { GameModule } from './modules/game/game.module';
import { GymnasiumModule } from './modules/gymnasium/gymnasium.module';
import { PlaygroundModule } from './modules/playground/playground.module';
import envConfig from '../config/env';
// import path from 'node:path';
import { resolve } from 'path';
import { EventToPlayerModule } from './modules/event-to-player/event-to-player.module';
import { GroupPlayerScoreModule } from './modules/group-player-score/group-player-score.module';
import { logDest } from './common/constant/constant';
import { APP_FILTER, APP_INTERCEPTOR } from '@nestjs/core';
import { AllExceptionsFilter } from './common/exceptionFilter';
import { SuccessInterceptor } from './common/interceptor/SuccessInterceptor';
import { StageEventModule } from './modules/stage-event/stage-event.module';
import { LoggingInterceptor } from './common/interceptor/LoggingInterceptor';
import { EventEmitterModule } from '@nestjs/event-emitter';
import { GameRuleModule } from './modules/game-rule/game-rule.module';
import { RallyRuleModule } from './modules/rally-rule/rally-rule.module';
import { PlayerSignupModule } from './modules/player-signup/player-signup.module';
import { RoleModule } from './modules/role/role.module';
import { PermissionModule } from './modules/permission/permission.module';
import { CommonModule } from './modules/common/common.module';
import { AuthModule } from './modules/auth/auth.module';
import { ScheduleModule } from '@nestjs/schedule';
import { CustomTypeORMLogger } from './common/utils/log';
// import { RedisModule } from 'nestjs-redis';
import { RedisModule, RedisModuleOptions } from '@nestjs-modules/ioredis';

const staticMiniApp = resolve(
  __dirname,
  '../../../match-management-app/dist/build/h5',
);
const staticAdmin = resolve(
  __dirname,
  '../../../badminton-competition-admin/dist',
);
const logPath = logDest;

@Module({
  imports: [
    EventEmitterModule.forRoot(),
    ServeStaticModule.forRoot({
      serveRoot: '/app',
      rootPath: staticMiniApp,
    }),
    ServeStaticModule.forRoot({
      serveRoot: '/admin',
      rootPath: staticAdmin,
    }),
    ServeStaticModule.forRoot({
      serveRoot: '/logs',
      rootPath: logPath,
    }),
    ServeStaticModule.forRoot({
      serveRoot: '/test',
      rootPath: resolve(__dirname, '../../../test'),
    }),
    ConfigModule.forRoot({
      isGlobal: true,
      envFilePath: [envConfig.path],
    }),
    ScheduleModule.forRoot(),
    RedisModule.forRoot({
      type: 'single',
      url: 'redis://127.0.0.1:6379',
      options: {
        redisOptions: {
          name: 'myuser',
          password: '123456',
          connectTimeout: 1000,
          maxRetriesPerRequest: 0, // 禁用重试以提高性能
          enableReadyCheck: false, // 禁用就绪检查
          // 连接池配置
          maxConnections: 100,
          minConnections: 10,
          // 优化数据处理
          enableAutoPipelining: true, // 启用自动管道
          autoPipeliningIgnoredCommands: [],
        },
      },
    } as RedisModuleOptions),
    TypeOrmModule.forRootAsync({
      imports: [ConfigModule],
      inject: [ConfigService],
      useFactory: async (configService: ConfigService) => ({
        type: 'mariadb', // 数据库类型
        // entities: [], // 数据表实体，synchronize为true时，自动创建表，生产环境建议关闭
        host: configService.get('DB_HOST'), // 主机，默认为localhost
        port: configService.get<number>('DB_PORT'), // 端口号
        username: configService.get('DB_USER'), // 用户名
        password: configService.get('DB_PASSWD'), // 密码
        database: configService.get('DB_DATABASE'), //数据库名
        timezone: '+08:00', //服务器上配置的时区
        synchronize: false, //根据实体自动创建数据库表， 生产环境建议关闭
        autoLoadEntities: true,
        maxQueryExecutionTime: 1000,
        // logging: ['error', 'info'],
        logging: process.env.NODE_ENV !== 'production',
        logger:
          process.env.NODE_ENV !== 'production'
            ? new CustomTypeORMLogger()
            : undefined,
        // subscribers: ['src/subscribers/*.ts'],
        // 添加连接池配置
        extra: {
          connectionLimit: 50, // 增加连接池大小
          waitForConnections: true,
          queueLimit: 0,
          acquireTimeout: 3000, // 添加获取连接超时时间
          enableKeepAlive: true, // 启用连接保活
          keepAliveInitialDelay: 30000, // 保活初始延迟
        },
      }),
    }),
    AuthModule,
    TournamentModule,
    CategoryModule,
    EventModule,
    StageModule,
    GroupModule,
    MatchModule,
    // TeamModule,
    UserModule,
    GameModule,
    GymnasiumModule,
    PlaygroundModule,
    EventToPlayerModule,
    GroupPlayerScoreModule,
    StageEventModule,
    GameRuleModule,
    RallyRuleModule,
    PlayerSignupModule,
    RoleModule,
    PermissionModule,
    CommonModule,
  ],
  controllers: [AppController],
  providers: [
    AppService,
    {
      provide: APP_FILTER,
      useClass: AllExceptionsFilter,
    },
    {
      provide: APP_INTERCEPTOR,
      useClass: SuccessInterceptor,
    },
    {
      provide: APP_INTERCEPTOR,
      useClass: LoggingInterceptor,
    },
    // {
    //   provide: APP_GUARD,
    //   useClass: RolesGuard,
    // },
  ],
})
export class AppModule {}
